<template>
  <el-form
    :label-position="labelPosition"
    label-width="auto"
    :model="form"
    style="max-width: 600px"
  >
    <el-form-item label="姓名" :label-position="itemLabelPosition">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="性别" :label-position="itemLabelPosition">
      <el-select v-model="form.sex" placeholder="Select" style="width: 240px">
        <el-option label="男" value="男" /> 
        <el-option label="女" value="女" />
    </el-select>
    </el-form-item>
    <el-form-item label="年龄" :label-position="itemLabelPosition">
      <el-input-number v-model="form.age" />
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="saveOrUser">{{ person ? '修 改' : '添 加'}}</el-button>
  <el-button type="info" @click="cancelUser">取 消</el-button>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormItemProps, FormProps } from 'element-plus'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const labelPosition = ref<FormProps['labelPosition']>('right')
const itemLabelPosition = ref<FormItemProps['labelPosition']>('')

//获取传递的参数
const person = history.state.person

onMounted(() => { 
  if(person){
    //将传递的参数赋值给form
   Object.assign(form,JSON.parse(person))
   //form.value = JSON.parse(person)
   form.flag = 'update'
  }
})

//实体类
const form = reactive({
  username: '',
  sex: '男',
  age: '',
  flag:'add',
  id:null
})
// const form = ref({
//   username: '',
//   sex: '男',
//   age: '',
//   flag:'add',
//   id:null
// })
//保存用户
const saveUser = () => {
  axios.post('/api/save.do',form).then(()=>{
    ElMessage({
      message: '保存成功.',
      type: 'success',
    })
  })
}
const router = useRouter()
//取消
const cancelUser = () => {
  router.push({path: '/showUser'})
}

//更新数据
const updateUser = () => {
  axios.post('/api/update.do',form).then(()=>{
    ElMessage({
      message: '更新成功.',
      type: 'success',
    })
  })
}

//保存或更新
const saveOrUser = () => {
  if(form.id){
    updateUser()   
  }else{
     saveUser()
  }
}
</script>
